package com.beiding.sqlbuilder.impl;

import com.beiding.sqlbuilder.Table;

import javax.management.relation.RoleUnresolved;
import java.util.*;

public class Tables {


    //无别称的表
    private Table noAliasTable;

    private Map<String, Table> aliasTableMap;

    public void addTables(Collection<Table> tables) {
        if (tables != null) {
            for (Table table : tables) {
                addTable(table);
            }
        }
    }

    public void addTable(Table table) {
        if (table.getAlias() == null) {
            if (noAliasTable == null) {
                noAliasTable = table;
            } else if (noAliasTable.getName().equals(table.getName())) {
                throw new RuntimeException("请使用不用的别称区分表名");
            }
        } else {
            if (aliasTableMap == null) {
                aliasTableMap = new HashMap<>();
                aliasTableMap.put(table.getAlias(), table);
            } else {
                Table t = aliasTableMap.get(table.getAlias());
                if (t == null) {
                    aliasTableMap.put(table.getAlias(), table);
                } else {
                    if (!table.getName().equals(t.getName())) {
                        throw new RuntimeException("两个不同的表不可使用相同的别称");
                    }
                }
            }
        }
    }


    public List<Table> getTables() {

        if (noAliasTable != null) {
            return Collections.singletonList(noAliasTable);
        }
        if (aliasTableMap == null) {
            return null;
        }
        return new ArrayList<>(aliasTableMap.values());
    }

}
